<template>
  <div>
    <table cellspacing="10">
      <thead>
        <th>序号</th>
        <th>单选</th>
        <th>商品名</th>
        <th>价格</th>
        <th>数量</th>
        <th>操作</th>
      </thead>
      <tr v-for="(item, index) in shops" :key="index">
        <td>{{ index + 1 }}</td>
        <td><input type="checkbox" v-model="checkList" :value="item"></td>
        <td>{{ item.name }}</td>
        <td>{{ item.price }}</td>
        <td><button @click="sub(index)">-</button><input type="text" v-model.number="item.number"><button
            @click="add(index)">+</button></td>
        <td><button @click="del(index, item)">删除</button></td>
      </tr>
      <tr>
        <td colspan="6">
          <div class="bottom">
            <input type="checkbox" @click="checkAll()" v-model="checked">全选<button>计算</button>一共需要支付{{ sum
            }}元<button>单独计算</button>只需支付{{ shopTotal }}元
          </div>
        </td>
      </tr>
    </table>
  </div>
</template>
<style scoped>
.bottom {
  display: flex;
}
</style>
<script>
export default {
  data() {
    return {
      checkList: [],//
      checked: false,
      shops: [
        { id: 1, name: "html", price: 55, number: 1 },
        { id: 2, name: "css", price: 66, number: 1 },
        { id: 3, name: "javascript", price: 77, number: 1 },
        { id: 4, name: "jq", price: 88, number: 1 },
      ],
    }
  },
  methods: {
    add(index) {
      this.shops[index].number++
    },
    sub(index) {
      if (this.shops[index].number > 1) {
        this.shops[index].number--
      }
    },
    del(index, item) {
      this.shops.splice(index, 1)
      // 去掉购物车里的商品
      for (const i in this.checkList) {
        if (this.checkList[i].id == item.id) {
          this.checkList.splice(i, 1)
        }
      }
    },
    checkAll() {
      if (this.checked) {
        this.checkList = []
      } else {
        this.checkList = []
        this.shops.forEach((item) => {
          this.checkList.push(item)
        })
      }
    }
  },
  computed: {
    sum() {
      return this.shops.reduce((total, item) => total + item.price * item.number, 0);
      /*
        let res = 0
        this.shops.forEach(item=>{
          res+=item.number * item.price
        })
  
      */
    },
    shopTotal() {
      let res = 0
      this.checkList.forEach(item => {
        res += item.number * item.price
      })
      return res
    }

  },
  watch: {
    checkList() {
      if (this.checkList.length === this.shops.length) {
        this.checked = true
      } else {
        this.checked = false
      }
      if (this.checkList.length == 0) {
        this.checked = false
      }
    }
  }
}
</script>